package java_thinking.unit_21._21_3;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @Desc:   3-10 使用ThreadLocal来维持线程封闭性
 * @author: cww
 * @DateTime: 2019/5/31 19:49
 */

public class ConnectionDispenser {
    static String DB_URL = "jdbc:mysql://localhost/mydatabase";
    /**
     * 当初次调用ThreadLocal.get() 就会调用initialValue()来获取初始值，线程的一些标识信息
     * 保存在Thread对象中，线程终止后，这些信息会作为垃圾回收
     */
    private ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {
        @Override
        public Connection initialValue() {
            try {
                return DriverManager.getConnection(DB_URL);
            } catch (SQLException e) {
                throw new RuntimeException("Unable to acquire Connection, e");
            }
        };
    };

    /**
     * get 一个connection的副本
     * @return
     */
    public Connection getConnection() {
        return connectionHolder.get();
    }
}
